import logging

from django.contrib.auth.forms import UserCreationForm
from django.core.cache import cache
from django.shortcuts import redirect, render
from django.template.context_processors import request
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView

from home.models import NavCategory, CourseCategory, Banner


# Create your views here.

class NavCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = NavCategory
        fields = ['id','name','display_name','weight','external_link']


logger = logging.getLogger('django')

class NavCategoryView(APIView):
    def get(self,request):
        try:
            queryset = NavCategory.objects.filter(is_show=True,is_deleted=False)
            ser = NavCategorySerializer(queryset,many=True)
            return Response({
                "code":1,
                "message":"SUCCESS",
                "data":ser.data
            })
        except Exception as e:
            logger.error(f"获取导航分类列表失败，失败原因：{e}")
            return Response({
                "code":10,
                "message":str(e),
                "data":[]
            })


class CourseCategorySerializer(serializers.ModelSerializer):

    # 这个字段来自一个方法：创建一个自定义的序列化字段
    children = serializers.SerializerMethodField()

    class Meta:
        model = CourseCategory
        fields = ['id','name','level','description','children']

    # 查询当前分类的所有的子分类
    # 路过没有子分类，递归查询子数据，并且序列化这个分类数据
    # 如果没有，返回空列表
    def get_children(self,obj):
        """
        :param obj: 模型
        :return:
        """
        print(obj)
        children = CourseCategory.objects.filter(parent=obj)

        if children:
            ser = CourseCategorySerializer(children,many=True)
            return ser.data
        else:
            return []

class CourseCategoryAPIView(APIView):
    def get(self,request):
        try:
            queryset = CourseCategory.objects.filter(is_show=True,is_deleted=False,level=1)
            ser = CourseCategorySerializer(queryset,many=True)
            logger.info(f"成功获取课程分类列表，共{len(ser.data)}条记录")
            return Response({
                "code":1,
                "message":"SUCCESS",
                "data":ser.data
            })
        except Exception as e:
            logger.error(f"获取课程分类列表失败，失败原因：{e}")
            return Response({
                "code":0,
                "message":str(e),
                "data":[]
            })



class BannerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Banner
        fields = ['id','image','link','note']

class BannerAPIView(APIView):
    def get(self,request):
        try:
            # 定义redis缓存的key，[项目名:业务名:业务数据]
            caches_key = "code_env_space:banner:list"
            # 从redis缓存中获取数据，通过key取value
            banner_redis = cache.get(caches_key)
            if banner_redis:
                logger.info(f"从缓存中获取轮播图列表")
                return Response({
                    "code":1,
                    "message":"SUCCESS FORM CACHE",
                    "data":banner_redis
                })
            # redis缓存中没有数据，从数据库中获取数据
            query_set = Banner.objects.filter(is_show=True,is_deleted=False)
            serializer = BannerSerializer(query_set,many=True)
            cache.set(caches_key,serializer.data,60*60*24)
            logger.info(f"成功从mysql获取轮播图列表，并更新到redis缓存，共{len(serializer.data)}条记录")
            return Response({
                "code":1,
                "message":"SUCCESS FORM MYSQL",
                "data":serializer.data
            })

        except Exception as e:
            logger.error(f"获取轮播图列表失败，失败原因：{e}")
            return Response({
                "code":0,
                "message":str(e),
                "data":[]
            })


def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("login")
        else:
            form = UserCreationForm()
        return render(request, "register.html",{"form":form})



















